#include "loc_comlink.h"
#include "loc_utils.h"



#define u8NOT_FOUND           (u8)0xFF
#define u8TIMEOUT_MAX           (u8)0xFF



static u8 u8ReceiveTimeOut;

static u8 u8FrameState;

static const u8	pu8FrameStart[]	= COM_u8FRAME_START;
static const u8	pu8FrameEnd[] 	= COM_u8FRAME_END;


extern BUF_tstrBuffer uartRxBuffer;

BUF_tstrBuffer  *strReceivedDataBuf;

void COM_vidInit(void)
{
    u8ReceiveTimeOut = TYP_u8ZERO;
    
    u8FrameState = COM_u8FRAME_NONE;

    strReceivedDataBuf = &uartRxBuffer;
}

u8 COM_u8ParseReceivedFrame(void)
{
    
    u8 u8FrameStartIndex;
    u8 u8FrameEndIndex;
    TYP_tu8Bool bBufferNotFull;
    
    bBufferNotFull = TYP_u8TRUE;
    

	if (u8FrameState == COM_u8FRAME_NONE)
	{
    	u8FrameStartIndex = BUF_u8SearchString(strReceivedDataBuf,TYP_u8ZERO, pu8FrameStart,COM_u8FRAME_START_LENGTH );
    
    	if (u8FrameStartIndex != u8NOT_FOUND)
    	{
       		u8FrameState = COM_u8FRAME_STARTED;

        	BUF_vidDumpFromFront(strReceivedDataBuf,u8FrameStartIndex);
		}
		else
		{
			bBufferNotFull = BUF_u8IsNotFull(strReceivedDataBuf);

            if (bBufferNotFull == TYP_u8FALSE)
            {
                BUF_vidFlush(strReceivedDataBuf);
                u8ReceiveTimeOut = TYP_u8ZERO;
                
            }
		}

	}
	else if (u8FrameState == COM_u8FRAME_STARTED )
	{
		u8ReceiveTimeOut++;
		u8FrameEndIndex = BUF_u8SearchString(strReceivedDataBuf,COM_u8FRAME_END_INDEX, pu8FrameEnd,COM_u8FRAME_END_LENGTH );
        
		
		if (u8FrameEndIndex == COM_u8FRAME_END_INDEX)
        {
            u8FrameState = COM_u8FRAME_ENDED;
            u8ReceiveTimeOut = TYP_u8ZERO;

        }
        else if (u8FrameEndIndex != u8NOT_FOUND)
        {
            BUF_vidDumpFromFront(strReceivedDataBuf,u8FrameEndIndex + COM_u8FRAME_END_LENGTH);
            u8ReceiveTimeOut = TYP_u8ZERO;
            u8FrameState = COM_u8FRAME_ERROR;
        }
        else
        {
            bBufferNotFull = BUF_u8IsNotFull(strReceivedDataBuf);

            if ((u8ReceiveTimeOut == u8TIMEOUT_MAX) || (bBufferNotFull == TYP_u8FALSE))
            {
                BUF_vidFlush(strReceivedDataBuf);
                u8ReceiveTimeOut = TYP_u8ZERO;
                u8FrameState = COM_u8FRAME_ERROR;
            }
        }
	}

	else if (u8FrameState == COM_u8FRAME_ERROR )
	{
		u8FrameState = COM_u8FRAME_NONE;
	}
	else
	{
	
	
	}



	

    return u8FrameState;
}

void COM_vidSetReceiveBuf(BUF_tstrBuffer *strRxBuffer)
{
    strReceivedDataBuf = strRxBuffer;
}

